<template>
  <Panel>
    <template #title>店铺管理</template>
    <template>
      <el-form
        :model="shopForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        size="mini"
      >
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="shopForm.name"></el-input>
        </el-form-item>

        <el-form-item label="店铺公告" prop="bulletin">
          <el-input type="textarea" v-model="shopForm.bulletin"></el-input>
        </el-form-item>

        <el-form-item label="商品头像">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5000/shop/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="" />
            <img
              v-else-if="shopForm.avatar"
              :src="base_url + shopForm.avatar"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="店铺图片">
          <el-upload
            action="http://localhost:5000/shop/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :file-list="shopForm.pics"
            :on-success="handlePicSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="配送费" prop="deliveryPrice">
          <el-input v-model="shopForm.deliveryPrice"></el-input>
        </el-form-item>

        <el-form-item label="配送时间" prop="deliveryTime">
          <el-input v-model="shopForm.deliveryTime"></el-input>
        </el-form-item>

        <el-form-item label="配送描述" prop="description">
          <el-input v-model="shopForm.description"></el-input>
        </el-form-item>

        <el-form-item label="店铺评分" prop="score">
          <el-input v-model="shopForm.score"></el-input>
        </el-form-item>

        <el-form-item label="销量" prop="sellCount">
          <el-input v-model="shopForm.sellCount"></el-input>
        </el-form-item>

        <el-form-item label="活动">
          <el-checkbox-group v-model="shopForm.supports">
            <el-checkbox label="在线支付满28减5" name="type"></el-checkbox>
            <el-checkbox label="VC无限橙果汁全场8折" name="type"></el-checkbox>
            <el-checkbox label="单人精彩套餐" name="type"></el-checkbox>
            <el-checkbox label="特价饮品8折抢购" name="type"></el-checkbox>
            <el-checkbox label="单人特色套餐" name="type"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="营业时间" required>
          <el-time-picker
            is-range
            v-model="shopForm.date"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >保存修改</el-button
          >
        </el-form-item>
      </el-form>
    </template>
  </Panel>
</template>

<script>
import { getShopInfo, editShopInfo } from '../../api/shop.js'
import _ from 'lodash'

export default {
  data() {
    return {
      dialogVisible: false,
      imageUrl: '',
      dialogImageUrl: '',
      shopForm: {
        name: '',
        bulletin: '',
        avatar: '',
        deliveryPrice: '',
        deliveryTime: '',
        description: '',
        score: '',
        sellCount: '',
        supports: [],
        date: []
      },
      rules: {
        name: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        bulletin: [
          { required: true, message: '请输入店铺公告', trigger: 'blur' }
        ],
        deliveryPrice: [
          { required: true, message: '请输入配送费', trigger: 'blur' }
        ],
        deliveryTime: [
          { required: true, message: '请输入配送时间', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        score: [{ required: true, message: '请输入评分', trigger: 'blur' }],
        sellCount: [{ required: true, message: '请输入销量', trigger: 'blur' }]
      },
      base_url: 'http://127.0.0.1:5000/upload/shop/',
      // 用来发请求的上传多张图片的数组
      uploadArr: []
    }
  },
  created() {
    this.getDatas()
  },
  methods: {
    async getDatas() {
      const { data } = await getShopInfo()
      // console.log(data)
      const arr = []
      data.pics.forEach(item => {
        // 在初次加载数据的时候，把图片列表里面的字段转存一份
        this.uploadArr.push(item)
        arr.push({
          name: item,
          url: this.base_url + item
        })
      })
      data.pics = arr
      this.shopForm = data
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 判断店铺头像和店铺图片列表是否为空
          if (this.shopForm.avatar === '' || this.uploadArr.length === 0) {
            this.$message({
              type: 'warning',
              message: '请上传店铺头像和图片!'
            })
          }

          // 先验证数据
          // console.log(this.shopForm)
          const cloneData = _.cloneDeep(this.shopForm)
          // 三个数组需要转换
          cloneData.date = JSON.stringify(cloneData.date)
          cloneData.pics = this.uploadArr
          cloneData.pics = JSON.stringify(cloneData.pics)
          cloneData.supports = JSON.stringify(cloneData.supports)
          const { code, msg } = await editShopInfo(cloneData)

          // console.log(data)
          if (code === 0) {
            this.$message({
              type: 'success',
              message: msg
            })

            setTimeout(() => {
              location.reload()
            }, 1500)
          }
        } else {
          //  console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // 把上传成功之后的图片地址存起来
      // this.$set(this, 'imgStr', res.imgUrl)
      this.shopForm.avatar = res.imgUrl
    },
    handlePicSuccess(res, file) {
      this.uploadArr.push(res.imgUrl)
    },
    beforeAvatarUpload(file) {
      const arr = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
      // const isJPG = file.type === 'image/jpeg'
      // includes 数组的方法，判断当前的值是否包含在数组中
      const isBool = arr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isBool) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isBool && isLt2M
    },
    handleRemove(file, fileList) {
      //  console.log(this.uploadArr)
      //  console.log(file.response.imgUrl)
      const i = this.uploadArr.findIndex(item => item === file.response.imgUrl)
      this.uploadArr.splice(i, 1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 193px;
}

/deep/ textarea {
  width: 300px;
  height: 80px;
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}

img {
  width: 128px;
}
</style>
